<?php

namespace app\data\controller\user;

use app\data\model\DataUserAccount;
use app\data\model\BaseUserUpgrade;
use app\data\model\DataUser;
use app\data\model\ShopOrder;
use app\data\model\DataUserCommission;
use app\data\service\UserAdminService;
use app\data\service\UserUpgradeService;
use think\admin\Controller;

/**
 * 普通用户管理
 * Class Admin
 * @package app\data\controller\user
 */
class Admin extends Controller
{
    /**
     * 普通用户管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        // 用户等级分组
        [$ts, $ls] = [[], BaseUserUpgrade::items()];
        $ts['ta'] = ['vip' => '', 'name' => '全部用户', 'count' => 0];
        $ts['t1'] = ['vip' => 1, 'name' => 'Vip用户', 'count' => 0];
        $ts['t0'] = ['vip' => 0, 'name' => '普通用户', 'count' => 0];
        $ts['to'] = ['vip' => '', 'name' => '其他用户', 'count' => 0];
        // 等级分组统计
        foreach (DataUser::mk()->field('is_vip,count(1) count')->group('is_vip')->cursor() as $v) {
            [$name, $count] = ["t{$v['is_vip']}", $v['count'], $ts['ta']['count'] += $v['count']];
            isset($ts[$name]) ? $ts[$name]['count'] += $count : '';
        }
        if (empty($ts['to']['count'])) unset($ts['to']);
        $this->total = $ts;

        // 设置页面标题
        $this->title = '普通用户管理';

        // 创建查询对象
        $query = DataUser::mQuery()->order('id desc');

        // 数据筛选选项
        $this->type = ltrim(input('type', 'ta'), 't');
        if (is_numeric($this->type)) $query->where(['is_vip' => $this->type]);

        // 分销用户搜索查询
        $db = DataUser::mQuery()->like('phone|username|nickname#from_keys')->db();
        if ($db->getOptions('where')) $query->whereRaw("pre_dis_id in {$db->field('id')->buildSql()}")->whereOrRaw("pre_pre_dis_id in {$db->field('id')->buildSql()}");

        // 数据查询分页
        $query = $query->like('phone|username|nickname#username')->equal('status,vip_code,is_distribution')
            ->dateBetween('create_at,vip_datetime,vip_expire');

        if(input('output') == 'json'){
            $query->page();
        }else{
            $lists = $query->page(true, false, false);
        }
        if (empty($lists['list']) === FALSE) {
            foreach ($lists['list'] as &$lv) {
                $detail = DataUser::mk()->where(['id'=>$lv['pre_dis_id']])->field('headimg,username,nickname,phone,is_vip')->find();
                $lv['from'] = $detail;

                //统计累计单数与金额
                $orderCount = ShopOrder::mk()->where(['uuid'=>$lv['id']])->whereIn('status','4,5,6')->count('id');
                $orderAmount = ShopOrder::mk()->where(['uuid'=>$lv['id']])->whereIn('status','4,5,6')->sum('payment_amount');
                if(empty($orderCount)) $orderCount = 0;
                if(empty($orderAmount)) {
                    $orderAmount = 0.00;
                }else{
                    $orderAmount = sprintf("%.2f",$orderAmount/100);
                }
                $lv['order_amount_total'] = $orderAmount;
                $lv['order_count'] = $orderCount;
                //佣金账户
                $lv['all_amount'] = 0;
                $lv['wait_amount'] = 0;
                $lv['used_amount'] = 0;
                $lv['withdraw_amount'] = 0;
                $lv['avail_amount'] = 0;
                $lv['freeze_amount'] = 0;
                $account = DataUserAccount::mk()->where(['uuid'=>$lv['id']])->field('avail_amount,all_amount,wait_amount,used_amount,withdraw_amount,freeze_amount')->find();
                if(empty($account) === FALSE){
                    $lv['all_amount'] = sprintf("%.2f",$account['all_amount']/100);
                    $lv['wait_amount'] = sprintf("%.2f",$account['wait_amount']/100);
                    $lv['used_amount'] = sprintf("%.2f",$account['used_amount']/100);
                    $lv['withdraw_amount'] = sprintf("%.2f",$account['withdraw_amount']/100);
                    $lv['avail_amount'] = sprintf("%.2f",$account['avail_amount']/100);
                    $lv['freeze_amount'] = sprintf("%.2f",$account['freeze_amount']/100);
                }

                //分销团队
                $lv['teams_users_direct'] = 0;
                $lv['teams_users_indirect'] = 0;
                $lv['teams_amount_direct'] = 0;
                $lv['teams_amount_indirect'] = 0;
                if($lv['is_distribution'] == 1){
                    $teams_users_direct = DataUser::mk()->where(['pre_dis_id'=>$lv['id']])->column('id');
                    $lv['teams_users_direct'] = count($teams_users_direct);
                    $teams_users_indirect = DataUser::mk()->where(['pre_pre_dis_id'=>$lv['id']])->column('id');
                    $lv['teams_users_direct'] = count($teams_users_indirect);
                    $teams_amount_direct = DataUserCommission::mk()->whereIn('product_uuid',$teams_users_direct)->whereIn('status','0,1')->where(['type'=>0])->sum('commission_amount');
                    $lv['teams_amount_direct'] = empty($teams_amount_direct) ? '0.00' : sprintf("%.2f",$teams_amount_direct/100);
                    $teams_amount_indirect = DataUserCommission::mk()->whereIn('product_uuid',$teams_users_indirect)->whereIn('status','0,1')->where(['type'=>0])->sum('commission_amount');
                    $lv['teams_amount_indirect'] = empty($teams_amount_indirect) ? '0.00' : sprintf("%.2f",$teams_amount_indirect/100);
                }
            }
        }
        $this->list = $lists['list'];
        $this->fetch();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        $this->upgrades = BaseUserUpgrade::items();
        UserAdminService::buildByUid($data, 'pre_dis_id', 'from');
    }

    /**
     * 用户团队关系
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function teams()
    {
        $this->title = '用户团队关系';
        $map = ['pid1' => input('from', 0)];
        DataUser::mQuery()->where($map)->page(false);
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _teams_page_filter(array &$data)
    {
        $uids = array_unique(array_column($data, 'id'));
        $subCount = DataUser::mk()->whereIn('pid1', $uids)->group('pid1')->column('count(1) count', 'pid1');
        foreach ($data as &$vo) $vo['subCount'] = $subCount[$vo['id']] ?? 0;
    }

    /**
     * 永久绑定代理
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function forever()
    {
        $map = $this->_vali(['id.require' => '用户ID不能为空！']);
        $user = DataUser::mk()->where($map)->find();
        if (empty($user) || empty($user['pid0'])) $this->error('用户不符合操作要求！');
        [$status, $message] = UserUpgradeService::bindAgent($user['id'], $user['pid0']);
        $status && sysoplog('前端用户管理', "修改用户[{$map['id']}]的代理为永久状态");
        empty($status) ? $this->error($message) : $this->success($message);
    }

    /**
     * 设为总部用户
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function unbind()
    {
        $map = $this->_vali(['id.require' => '用户ID不能为空！']);
        $user = DataUser::mk()->where($map)->findOrEmpty();
        if ($user->isEmpty()) $this->error('用户不符合操作要求！');
        // 修改指定用户代理数据
        $user->save(['pid0' => 0, 'pid1' => 0, 'pid2' => 0, 'pids' => 1, 'path' => '-', 'layer' => 1]);
        // 刷新用户等级及上级等级
        UserUpgradeService::upgrade($user['id'], true);
        sysoplog('前端用户管理', "设置用户[{$map['id']}]为总部用户");
        $this->success('设为总部用户成功！');
    }

    /**
     * 绑定上级代理
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function parent()
    {
        if ($this->request->isGet()) {
            $this->upgrades = BaseUserUpgrade::items();
            $data = $this->_vali(['uuid.require' => '待操作UID不能为空！']);

            // 排除下级用户
            $path = DataUser::mk()->where(['id' => $data['uuid']])->value('path', '-');
            $subids = DataUser::mk()->whereLike('path', "{$path}{$data['uuid']}-%")->column('id');
            $query = DataUser::mQuery()->order('id desc')->whereNotIn('id', array_merge($subids, array_values($data)));

            // 用户搜索查询
            $db = DataUser::mQuery()->equal('vip_code#from_vipcode')->like('phone#from_phone,username|nickname#from_username')->db();
            if ($db->getOptions('where')) $query->whereRaw("pid1 in {$db->field('id')->buildSql()}");

            // 数据查询分页
            $query->like('phone,username|nickname#username')->whereRaw('vip_code>0')->equal('status,vip_code')->dateBetween('create_at')->page();
        } else {
            $data = $this->_vali(['pid.require' => '待绑定代理不能为空！', 'uuid.require' => '待操作用户不能为空！']);
            [$status, $message] = UserUpgradeService::bindAgent($data['uuid'], $data['pid'], 2);
            $status && sysoplog('前端用户管理', "修改用户[{$data['uuid']}]的代理为用户[{$data['pid']}]");
            empty($status) ? $this->error($message) : $this->success($message);
        }
    }

    /**
     * 重算用户余额返利
     * @auth true
     */
    public function sync()
    {
        $this->_queue('重新计算用户余额返利', 'xdata:UserAmount');
    }

    /**
     * 修改用户状态
     * @auth true
     */
    public function state()
    {
        DataUser::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }
    /**
     * 升级会员
     * @auth true
     */
    public function updatevip()
    {
        $id = input('id','','trim,intval');
        $uinfo = DataUser::mk()->where(['id'=>$id])->find()->toArray();
        if(empty($uinfo)){
            return \Tools::returnMsg(false,array(
                'code'  => '10015',
                'message'=>'参数错误'
            ));
        }
        sysoplog('手动升级会员',"管理员：".session('user.username').'将'.$uinfo['username'].'升级为年度会员，有效期至：'.\Tools::getDateTimeByTime(strtotime("+1 year")));
        DataUser::mSave(array(
            'vip_datetime'  => \Tools::getDateTimeByTime(),
            'vip_expire'    => \Tools::getDateTimeByTime(strtotime("+1 year")),
            'is_vip'        => 1
        ));
    }

}
